package com.qsl.account.service.impl;

import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qsl.account.entity.Account;
import com.qsl.account.mapper.AccountMapper;
import com.qsl.account.service.AccountService;
import com.qsl.account.vo.AccountVo;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Objects;

/***
 * @description account service impl
 * @author 青石路
 * @date 2022/1/9 17:49
 */
@Service
public class AccountServiceImpl extends ServiceImpl<AccountMapper, Account> implements AccountService {

    @Override
    public AccountVo getAccountVo(Long accountId) {
        Account account = getById(accountId);
        if (Objects.isNull(account)) {
            return null;
        }
        AccountVo accountVo = new AccountVo();
        BeanUtils.copyProperties(account, accountVo);
        return accountVo;
    }

    @Override
    public boolean debit(Long userId, BigDecimal money) {
        LambdaUpdateWrapper<Account> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(Account::getUserId, userId).ge(Account::getBalance, money)
                .setSql("balance = balance - " + money);
        boolean update = this.update(updateWrapper);
        if (!update) {
            throw new RuntimeException("账户余额不足");
        }
        return true;
    }
}
